<template>
  <div class="time-thief-container">
    <div class="game-area" ref="gameBoard" tabindex="0" @click="handleClick" @mousemove="handleMouseMove">
      <!-- 游戏状态栏 -->
      <div class="game-header" :class="{ 'danger': timeLeft < 30, 'loan-active': isLoanActive }">
        <div class="time-display">
          <span class="time-icon">⌛</span>
          <span class="time-value">{{ formatTime(timeLeft) }}</span>
        </div>
        <div class="coin-display">
          <span class="coin-icon">💰</span>
          <span class="coin-value">{{ coins }}</span>
        </div>
      </div>

      <!-- 游戏主区域 -->
      <div class="game-world" :class="{ 'time-critical': timeLeft < 30 }">
        <!-- 玩家角色 -->
        <div class="player" :style="playerStyle">
          <div class="player-sprite"></div>
        </div>

        <!-- 时间硬币 -->
        <div v-for="coin in gameCoins" 
             :key="coin.id" 
             class="coin" 
             :class="{ 'frenzy': isFrenzyActive }"
             :style="{ left: coin.x + 'px', top: coin.y + 'px' }">
        </div>

        <!-- 敌人 -->
        <div v-for="enemy in enemies" 
             :key="enemy.id" 
             class="enemy"
             :class="enemy.type"
             :style="{ left: enemy.x + 'px', top: enemy.y + 'px' }">
        </div>
      </div>

      <!-- 道具栏 -->
      <div class="item-bar">
        <button class="item-button" 
                @click="activateTimeBomb"
                :disabled="coins < 30 || isTimeBombActive">
          时间炸弹 (30)
        </button>
        <button class="item-button" 
                @click="activateMirror"
                :disabled="coins < 45 || isMirrorActive">
          分身镜像 (45)
        </button>
        <button class="item-button" 
                @click="activateTimeLoan"
                :disabled="isLoanActive">
          时间借贷
        </button>
      </div>

      <!-- 游戏结束弹窗 -->
      <div v-if="gameOver" class="game-over">
        <h2>游戏结束</h2>
        <p>最终得分: {{ coins }}</p>
        <p>坚持时间: {{ formatTime(totalTime) }}</p>
        <button class="restart-button" @click="restartGame">重新开始</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 游戏配置
const INITIAL_TIME = 60
const COIN_VALUE = 3
const ENEMY_PENALTY = 15
const COIN_SPAWN_INTERVAL = 1000
const ENEMY_SPAWN_INTERVAL = 3000

// 游戏状态
const timeLeft = ref(INITIAL_TIME)
const coins = ref(0)
const gameCoins = ref([])
const enemies = ref([])
const playerPos = ref({ x: 0, y: 0 })
const clickCount = ref(0)
const gameOver = ref(false)
const totalTime = ref(0)

// 特殊状态
const isLoanActive = ref(false)
const isFrenzyActive = ref(false)
const isTimeBombActive = ref(false)
const isMirrorActive = ref(false)

// 游戏循环
let gameLoop = null
let coinSpawnLoop = null
let enemySpawnLoop = null

// 计算玩家样式
const playerStyle = computed(() => ({
  left: `${playerPos.value.x}px`,
  top: `${playerPos.value.y}px`
}))

// 格式化时间
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 生成硬币
const spawnCoin = () => {
  const gameBoard = document.querySelector('.game-world')
  if (!gameBoard) return

  const { width, height } = gameBoard.getBoundingClientRect()
  gameCoins.value.push({
    id: Date.now(),
    x: Math.random() * (width - 30),
    y: Math.random() * (height - 30)
  })
}

// 生成敌人
const spawnEnemy = () => {
  const types = ['patrol', 'chaser', 'lurker', 'manager']
  const type = types[Math.floor(Math.random() * types.length)]
  
  const gameBoard = document.querySelector('.game-world')
  if (!gameBoard) return

  const { width, height } = gameBoard.getBoundingClientRect()
  enemies.value.push({
    id: Date.now(),
    type,
    x: Math.random() * (width - 40),
    y: Math.random() * (height - 40),
    speed: type === 'chaser' ? 3 : 1
  })
}

// 更新游戏状态
const updateGame = () => {
  if (gameOver.value) return

  // 更新时间
  if (isLoanActive.value) {
    timeLeft.value -= 2
  } else {
    timeLeft.value -= 1
  }

  // 检查游戏结束
  if (timeLeft.value <= 0) {
    endGame()
    return
  }

  // 更新敌人位置
  updateEnemies()

  // 检查碰撞
  checkCollisions()
}

// 更新敌人位置
const updateEnemies = () => {
  enemies.value.forEach(enemy => {
    if (isTimeBombActive.value) return

    switch (enemy.type) {
      case 'chaser':
        // 追踪玩家
        const dx = playerPos.value.x - enemy.x
        const dy = playerPos.value.y - enemy.y
        const dist = Math.sqrt(dx * dx + dy * dy)
        if (dist > 0) {
          enemy.x += (dx / dist) * enemy.speed
          enemy.y += (dy / dist) * enemy.speed
        }
        break
      case 'patrol':
        // 巡逻移动
        enemy.x += Math.cos(Date.now() / 1000) * enemy.speed
        enemy.y += Math.sin(Date.now() / 1000) * enemy.speed
        break
      // ... 其他敌人类型的移动逻辑
    }
  })
}

// 检查碰撞
const checkCollisions = () => {
  const playerRadius = 20
  
  // 检查硬币碰撞
  gameCoins.value = gameCoins.value.filter(coin => {
    const dx = playerPos.value.x - coin.x
    const dy = playerPos.value.y - coin.y
    const dist = Math.sqrt(dx * dx + dy * dy)
    
    if (dist < playerRadius + 15) {
      collectCoin()
      return false
    }
    return true
  })

  // 检查敌人碰撞
  enemies.value.forEach(enemy => {
    if (isTimeBombActive.value) return

    const dx = playerPos.value.x - enemy.x
    const dy = playerPos.value.y - enemy.y
    const dist = Math.sqrt(dx * dx + dy * dy)
    
    if (dist < playerRadius + 20) {
      hitByEnemy()
    }
  })
}

// 收集硬币
const collectCoin = () => {
  const value = isFrenzyActive.value ? COIN_VALUE * 2 : COIN_VALUE
  const bonus = isLoanActive.value ? value * 2 : value
  
  timeLeft.value += bonus
  coins.value++
  clickCount.value++

  // 检查连击
  if (clickCount.value >= 10) {
    activateFrenzy()
  }
}

// 被敌人击中
const hitByEnemy = () => {
  timeLeft.value -= ENEMY_PENALTY
  if (timeLeft.value <= 0) {
    endGame()
  }
}

// 激活时间狂热
const activateFrenzy = () => {
  isFrenzyActive.value = true
  setTimeout(() => {
    isFrenzyActive.value = false
    clickCount.value = 0
  }, 5000)
}

// 激活时间炸弹
const activateTimeBomb = () => {
  if (coins.value < 30) return
  
  coins.value -= 30
  isTimeBombActive.value = true
  setTimeout(() => {
    isTimeBombActive.value = false
  }, 5000)
}

// 激活分身镜像
const activateMirror = () => {
  if (coins.value < 45) return
  
  coins.value -= 45
  isMirrorActive.value = true
  
  // 自动收集范围内的硬币
  const mirrorInterval = setInterval(() => {
    gameCoins.value = gameCoins.value.filter(coin => {
      const dx = playerPos.value.x - coin.x
      const dy = playerPos.value.y - coin.y
      const dist = Math.sqrt(dx * dx + dy * dy)
      
      if (dist < 100) {
        collectCoin()
        return false
      }
      return true
    })
  }, 500)

  setTimeout(() => {
    isMirrorActive.value = false
    clearInterval(mirrorInterval)
  }, 20000)
}

// 激活时间借贷
const activateTimeLoan = () => {
  if (isLoanActive.value) return
  
  isLoanActive.value = true
  setTimeout(() => {
    isLoanActive.value = false
  }, 15000)
}

// 处理点击
const handleClick = (event) => {
  const rect = event.target.getBoundingClientRect()
  playerPos.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  }
}

// 处理鼠标移动
const handleMouseMove = (event) => {
  const rect = event.target.getBoundingClientRect()
  playerPos.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  }
}

// 结束游戏
const endGame = () => {
  gameOver.value = true
  clearInterval(gameLoop)
  clearInterval(coinSpawnLoop)
  clearInterval(enemySpawnLoop)
}

// 重启游戏
const restartGame = () => {
  timeLeft.value = INITIAL_TIME
  coins.value = 0
  gameCoins.value = []
  enemies.value = []
  clickCount.value = 0
  gameOver.value = false
  isLoanActive.value = false
  isFrenzyActive.value = false
  isTimeBombActive.value = false
  isMirrorActive.value = false
  
  startGame()
}

// 开始游戏
const startGame = () => {
  gameLoop = setInterval(updateGame, 1000)
  coinSpawnLoop = setInterval(spawnCoin, COIN_SPAWN_INTERVAL)
  enemySpawnLoop = setInterval(spawnEnemy, ENEMY_SPAWN_INTERVAL)
}

// 生命周期钩子
onMounted(() => {
  startGame()
})

onUnmounted(() => {
  clearInterval(gameLoop)
  clearInterval(coinSpawnLoop)
  clearInterval(enemySpawnLoop)
})
</script>

<style scoped>
.time-thief-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: var(--theme-container-bg, #1a1a1a);
}

.game-area {
  width: 800px;
  height: 600px;
  position: relative;
  background-color: var(--theme-bg, #2d2d2d);
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.game-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}

.game-header.danger {
  background-color: rgba(239, 68, 68, 0.5);
  animation: pulse 1s infinite;
}

.game-header.loan-active {
  background-color: rgba(168, 85, 247, 0.5);
}

.game-world {
  flex: 1;
  position: relative;
  background: linear-gradient(45deg, #1a1a1a 25%, #2d2d2d 25%, #2d2d2d 50%, #1a1a1a 50%, #1a1a1a 75%, #2d2d2d 75%, #2d2d2d);
  background-size: 20px 20px;
  animation: backgroundScroll 20s linear infinite;
}

.game-world.time-critical::before {
  content: '';
  position: absolute;
  inset: 0;
  border: 4px solid rgba(239, 68, 68, 0.5);
  pointer-events: none;
}

.player {
  position: absolute;
  width: 40px;
  height: 40px;
  transform: translate(-50%, -50%);
  transition: all 0.1s;
}

.player-sprite {
  width: 100%;
  height: 100%;
  background-color: var(--theme-primary-color, #3b82f6);
  border-radius: 50%;
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
}

.coin {
  position: absolute;
  width: 30px;
  height: 30px;
  background-color: #fbbf24;
  border-radius: 50%;
  animation: rotate 2s linear infinite;
}

.coin.frenzy {
  animation: rotate 1s linear infinite, glow 0.5s infinite alternate;
}

.enemy {
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.enemy.patrol {
  background-color: #ef4444;
}

.enemy.chaser {
  background-color: #8b5cf6;
  clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}

.enemy.lurker {
  background-color: #10b981;
  opacity: 0.5;
}

.enemy.manager {
  background-color: #f59e0b;
  clip-path: circle(50% at 50% 50%);
}

.item-bar {
  padding: 10px;
  display: flex;
  gap: 10px;
  background-color: rgba(0, 0, 0, 0.5);
}

.item-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.item-button:disabled {
  background-color: var(--theme-secondary-color, #4b5563);
  cursor: not-allowed;
}

.game-over {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
}

.restart-button {
  margin-top: 20px;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  cursor: pointer;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes glow {
  from { box-shadow: 0 0 5px #fbbf24; }
  to { box-shadow: 0 0 20px #fbbf24; }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

@keyframes backgroundScroll {
  from { background-position: 0 0; }
  to { background-position: 40px 40px; }
}
</style> 